//
//  CLDeviceIOS.m
//
//
//  Created by xinxiang on 13-1-17.
//  Copyright (c) 2013年 xinxiang. All rights reserved.
//  获取设备信息
//

#import "CLDeviceIOS.h"
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
#import "Reachability.h"
#import "sys/utsname.h"   
#import <CoreLocation/CoreLocation.h>
#import <SystemConfiguration/CaptiveNetwork.h>
#import "CLEncoder.h"

@import CoreTelephony;

@interface CLDeviceIOS()
@property (nonatomic, strong) CTCallCenter * callCenter;
@end

@implementation CLDeviceIOS

static CLDeviceIOS *sharedDevice=nil;


@synthesize mac;
@synthesize sys_version;
@synthesize lang;
@synthesize net_type;
@synthesize locServerEnable = _locServerEnable;

+(CLDeviceIOS *) single
{
    @synchronized(self)
    {
        if (sharedDevice == nil)
        {
            sharedDevice = [[self alloc] init];
            sharedDevice.callCenter = [[CTCallCenter alloc] init];
        }
    }
    return  sharedDevice;
}

+ (void)setForNew
{
    @synchronized(self)
    {
        sharedDevice = [[self alloc] init];
    }
}

- (CLDeviceIOS *)init
{
    self=[super init];
    if (self) {
        DLog(@"...CLDeviceIOS init...");
        sys_version=[[UIDevice currentDevice]systemVersion];
        mac=[self macAddress];
        lang = [CLDeviceIOS deviceIOSLanguage];
        _languageType = [CLDeviceIOS isChineseLanguageType]?CLDeviceIOSLanguageTypeChinese:CLDeviceIOSLanguageTypeEnglish;

//        self.saveToPhotos = [CLSeverTool getSaveToPhotosFlag];
//        self.token = [ClSeverTool getTokenFromUserFile];
        self.is_onlone = [self IsEnableNetwork];
        _locServerEnable = [self isEnableLocationServer];
    }
    return self;
}

- (BOOL)locServerEnable
{
    _locServerEnable = [self isEnableLocationServer];
    return _locServerEnable;
}

- (NSString *) macAddress
{
    int                 mib[6];
    size_t              len;
    char                *buf;
    unsigned char       *ptr;
    struct if_msghdr    *ifm;
    struct sockaddr_dl  *sdl;
    mib[0] = CTL_NET;
    mib[1] = AF_ROUTE;
    mib[2] = 0;
    mib[3] = AF_LINK;
    mib[4] = NET_RT_IFLIST;
    if ((mib[5] = if_nametoindex("en0")) == 0) {
        DLog("Error: if_nametoindex error/n");
        return nil;
    }
    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
        DLog("Error: sysctl, take 1/n");
        return nil;
    }
    if ((buf = malloc(len)) == NULL) {
        DLog("Could not allocate memory. error!/n");
        return nil;
    }
    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        free(buf);
        DLog("Error: sysctl, take 2");
        return nil;
    }
    ifm = (struct if_msghdr *)buf;
    sdl = (struct sockaddr_dl *)(ifm + 1);
    ptr = (unsigned char *)LLADDR(sdl);

    NSString *outstring = [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    free(buf);
    return [outstring uppercaseString];
}

- (NSString *)deviceModel
{
    // 机型
    NSString *model = [UIDevice currentDevice].model;
    DLog(@"model: %@", model);
    DLog(@"name: %@",[UIDevice currentDevice].name);
    DLog(@"localizedModel: %@",[UIDevice currentDevice].localizedModel);
    DLog(@"systemName: %@",[UIDevice currentDevice].systemName);
    DLog(@"systemVersion: %@",[UIDevice currentDevice].systemVersion);
    DLog(@"device: %@",[[UIDevice currentDevice] description]);
    return model;
}
-(NSString *)deviceInfo
{
    NSMutableString *info=[[NSMutableString alloc] init];
    
    
    if (self.mac) {
        [info appendString:@"&mac="];
        [info appendString:self.mac];
    }

    [info appendFormat:@"&sys_version=%@", self.sys_version];
    [info appendFormat:@"&model=%@", [UIDevice currentDevice].model];
    [info appendFormat:@"&lang=%@", self.lang];
    [info appendFormat:@"&net_type=%@", self.net_type];
    [info appendFormat:@"&app_version=%@", self.app_version];
    [info appendFormat:@"&app_build=%ld",(long)self.app_build];
    if (self.token.length > 5) {
        [info appendFormat:@"&token=%@",self.token];
    }
    return info;
}

-(NSString *)deviceInfoEncode
{
    NSMutableString *info=[[NSMutableString alloc] init];
   
    NSString *macEncode = [CLEncoder ASCEncode:self.mac];
    if (macEncode) {
        [info appendString:@"&mac="];
        [info appendString:macEncode];
    }
    NSString *wifiMac = [CLDeviceIOS wifiMacEncode];
    if (wifiMac.length > 3) {
        [info appendFormat:@"&wifi=%@",wifiMac];
    }
    [info appendFormat:@"&sys_version=%@", self.sys_version];
    [info appendFormat:@"&model=%@", [[UIDevice currentDevice]model]];
    [info appendFormat:@"&lang=%@", self.lang];
    [info appendFormat:@"&net_type=%@", self.net_type];
    [info appendFormat:@"&app_version=%@", self.app_version];
    [info appendFormat:@"&app_build=%ld",(long)self.app_build];
    if (self.token.length > 5) {
        [info appendFormat:@"&token=%@",self.token];
    }
    return info;
}

- (void) load
{
    DLog(@"load device info data");
}

// 是否wifi
- (BOOL) IsEnableWIFI {
    return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
}

// 是否3G
+ (BOOL) IsEnable3G {
    return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);
}

// 是否开启网络
- (BOOL) IsEnableNetwork {
    return  [self IsEnableWIFI] || [CLDeviceIOS IsEnable3G];
}

//定位否服是否打开
- (BOOL) isEnableLocationServer{
    BOOL enable = NO;
    if ([CLLocationManager locationServicesEnabled]) {
        if (SysVerValue < 8) {
            if([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized){
                enable = YES;
            }
        }else{
            switch ([CLLocationManager authorizationStatus]) {
                case kCLAuthorizationStatusAuthorizedAlways:
                case kCLAuthorizationStatusAuthorizedWhenInUse:
                    enable = YES;
                    break;
                default:
                    break;
            }
        }
    }
    
    return enable;
}

+ (NSString *)wifiMacEncode
{
    NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
    DLog(@"Supported interfaces: %@", ifs);
    id info = nil;
    for (NSString *ifnam in ifs) {
        info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        DLog(@"%@ => %@", ifnam, info);
        if (info && [info count]) {
            break;
        }
    }
    id macTemp = [info objectForKey:@"BSSID"];
    if (macTemp == nil) {
        return nil;
    }
    NSString *macStr = [NSString stringWithFormat:@"%@",macTemp];
    
    NSArray *macSubs = [macStr componentsSeparatedByString:@":"];
    
    NSMutableString *MAC = [[NSMutableString alloc] initWithCapacity:17];
    
    for (int i = 0; i< [macSubs count]; i++) {
        
        if (i > 0) {
            
            [MAC appendString:@":"];
            
        }
        
        NSString *str = [macSubs objectAtIndex:i];
        
        if (str.length == 1) {
            
            [MAC appendFormat:@"0%@",str];
            
        }else{
            
            [MAC appendString:str];
            
        }
        
    }
    
    DLog(@"MAC of wifi: %@",MAC);

    NSString *encodeMac = [CLEncoder ASCEncode:MAC];
    if(encodeMac){
        return [NSString stringWithFormat:@"%@,99,%@",encodeMac,[info objectForKey:@"SSID"]];
    }
    return nil;
}

+ (NSString *)wifiMac
{
    NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
    DLog(@"Supported interfaces: %@", ifs);
    id info = nil;
    for (NSString *ifnam in ifs) {
        info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        DLog(@"%@ => %@", ifnam, info);
        if (info && [info count]) {
            break;
        }
    }
    id macTemp = [info objectForKey:@"BSSID"];
    if (macTemp == nil) {
        return nil;
    }
    NSString *macStr = [NSString stringWithFormat:@"%@",macTemp];
    
    NSArray *macSubs = [macStr componentsSeparatedByString:@":"];
    
    NSMutableString *MAC = [[NSMutableString alloc] initWithCapacity:17];
    
    for (int i = 0; i< [macSubs count]; i++) {
        
        if (i > 0) {
            
            [MAC appendString:@":"];
            
        }
        
        NSString *str = [macSubs objectAtIndex:i];
        
        if (str.length == 1) {
            
            [MAC appendFormat:@"0%@",str];
            
        }else{
            
            [MAC appendString:str];
            
        }
        
    }
    
    DLog(@"MAC of wifi: %@",MAC);
    return [CLEncoder ASCEncode:MAC];
}


#pragma mark -获取WIFI列表

//获取到手机WIFI
+ (CLWifiMsgModel *)getiphoneWifi{
    
    NSDictionary *dict = [CLDeviceIOS fetchSSIDInfo];
    CLWifiMsgModel *wifiMsgModel = [[CLWifiMsgModel alloc]init];
    wifiMsgModel.mac = dict[@"BSSID"];
    wifiMsgModel.ssid = dict[@"SSID"];
    return wifiMsgModel;
}

CFArrayRef
CNCopySupportedInterfaces	(void)__OSX_AVAILABLE_STARTING(__MAC_10_8,__IPHONE_4_1);
//通过CNCopySupportedInterfaces获取wifi列表，实际测试中返回数组中只有一个值，即当前连接的wifi。


+ (id)fetchSSIDInfo
{
    NSString *currentSSID = @"";
    CFArrayRef myArray = CNCopySupportedInterfaces();
    if (myArray != nil){
        NSDictionary* myDict = (__bridge NSDictionary *) CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0));
        if (myDict!=nil){
            currentSSID=[myDict valueForKey:@"SSID"];
        } else {
            currentSSID=@"<<NONE>>";
        }
    } else {
        currentSSID=@"<<NONE>>";
    }
    
    NSArray *ifs = (__bridge id)CNCopySupportedInterfaces();
    //    NSLog(@"%s: Supported interfaces: %@", __func__, ifs);
    id info = nil;
    for (NSString *ifnam in ifs) {
        info = (__bridge id)CNCopyCurrentNetworkInfo((CFStringRef)CFBridgingRetain(ifnam));
        if (info && [info count]) {
            break;
        }
    }
    return info;
}



/**
 *  语言判断统一接口，由于iOS升级会造成语言判断条件改变，因此进行统一
 */
+ (NSString *)deviceIOSLanguage
{
    // 系统语言
    NSArray *arLanguages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
    NSString *strLang = [arLanguages firstObject];
    DLog(@"LANG:%@",strLang);
    
    
    // 服务器根据zh-CN与en进行语言的对比判断
    if ([strLang hasPrefix:@"zh-"]) {
        return @"zh-CN";
    } else {
        return @"en";
    }
}

+ (BOOL)isChineseLanguageType
{
    return [[self deviceIOSLanguage] isEqualToString:@"zh-CN"];
}

#pragma mark -来电、短信监听
- (void) aboutCall{
    //获取电话接入信息
    self.callCenter.callEventHandler = ^(CTCall *call){
        if ([call.callState isEqualToString:CTCallStateDisconnected]){
            DLog(@"Call has been disconnected");
            
        }else if ([call.callState isEqualToString:CTCallStateConnected]){
            DLog(@"Call has just been connected");
            
        }else if([call.callState isEqualToString:CTCallStateIncoming]){
            DLog(@"Call is incoming");
            
        }else if ([call.callState isEqualToString:CTCallStateDialing]){
            DLog(@"call is dialing");
            
        }else{
            DLog(@"Nothing is done");
        }
    };
}

/**
 *  获取运营商信息
 */
- (void)getCarrierInfo{
    // 获取运营商信息
    CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = info.subscriberCellularProvider;
    NSLog(@"carrier:%@", [carrier description]);
    
    // 如果运营商变化将更新运营商输出
    info.subscriberCellularProviderDidUpdateNotifier = ^(CTCarrier *carrier) {
        NSLog(@"carrier:%@", [carrier description]);
    };
    
    // 输出手机的数据业务信息
    NSLog(@"Radio Access Technology:%@", info.currentRadioAccessTechnology);
}


//app信息
- (NSString*)app_version{
    NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
    _app_version = [infoDict objectForKey:@"CFBundleShortVersionString"];
    return _app_version;
}

- (NSInteger)app_build{
    NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
    _app_build = [[infoDict objectForKey:@"CFBundleVersion"] integerValue];
    return _app_build;
}

#warning 测试
- (NSString *)device_id{

    return @"717841";
}

@end
